import { Image as AntImage } from 'antd';
import { ImageProps } from 'antd/es/image';
import { compHoc, IUPComponent, TypeExtends } from '../util';

type TypeProps<T> = TypeExtends<
  T,
  {
    onChange?: (value: any) => void;
    value?: string;
  }
>;

export const Image = compHoc<TypeProps<ImageProps>>(
  class extends IUPComponent {
    constructor(props) {
      super(props);
      this.state.value = props.defaultValue;
    }

    static getDerivedStateFromProps(nextProps, prevState) {
      return IUPComponent.propsToState(nextProps, prevState, ['value', 'src|value']);
    }

    setValue(value, cb?) {
      if (this.state.value === value) {
        return;
      }
      this.setState(
        (prev) => ({ ...prev, value }),
        () => {
          this.props.onChange && this.props.onChange(value);
          cb && cb(value);
        }
      );
    }

    getValue() {
      return this.state.value;
    }

    render() {
      const { value, observer, ...others } = this.props;
      return (
        <AntImage
          loading="lazy"
          fallback=""
          {...others}
          src={value ?? ''}
        />
      );
    }
  },
  'Image'
);
